<template>
  <div class="app">
    <!-- Cesium地球视图 - 填充整个屏幕 -->
    <div id="cesiumContainer"></div>
    
    <!-- 左侧模型控制面板 -->
    <ControlPanel 
      :loading="loading"
      :has-model="!!currentModel"
      @load-model="handleLoadModel"
      @load-test-cube="handleLoadTestCube"
      @remove-model="handleRemoveModel"
      @center-on-model="handleCenterOnModel"
      @update-position="handleUpdatePosition"
      @update-orientation="handleUpdateOrientation"
      @update-scale="handleUpdateScale"
      class="left-panel"
    />
    
    <!-- 右侧视图工具栏 -->
    <ViewToolbar 
      :cesium-manager="cesiumManager"
      @reset-view="handleResetView"
      @fly-to-location="handleFlyToLocation"
      @change-view-mode="handleChangeViewMode"
      @change-basemap="handleChangeBasemap"
      @update-camera-height="handleUpdateCameraHeight"
      @toggle-terrain="handleToggleTerrain"
      @toggle-atmosphere="handleToggleAtmosphere"
      @toggle-lighting="handleToggleLighting"
      @save-view="handleSaveView"
      class="right-panel"
    />
    
    <!-- 底部信息面板 -->
    <InfoPanel 
      :coordinates="coordinates"
      :model-info="modelInfo"
      :camera-info="cameraInfo"
      class="bottom-panel"
    />
    
    <!-- 加载提示 -->
    <LoadingIndicator 
      v-if="loading"
      :message="loadingMessage"
    />
    
    <!-- 顶部标题栏 -->
    <div class="title-bar">
      <h1>Cesium + Revit 三维模型展示系统</h1>
      <div class="title-actions">
        <button @click="toggleFullscreen" class="title-btn" title="全屏">
          📺
        </button>
        <button @click="toggleHelp" class="title-btn" title="帮助">
          ❓
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import * as Cesium from 'cesium'
import ControlPanel from './components/ControlPanel.vue'
import ViewToolbar from './components/ViewToolbar.vue'
import InfoPanel from './components/InfoPanel.vue'
import LoadingIndicator from './components/LoadingIndicator.vue'
import { CesiumManager } from './core/cesium-manager'
import { ModelLoader } from './core/model-loader'
import type { ModelPosition, ModelOrientation } from './types/model'

// 响应式数据
const loading = ref(true)
const loadingMessage = ref('正在初始化Cesium...')
const coordinates = ref({ longitude: 0, latitude: 0 })
const modelInfo = ref('未加载模型')
const cameraInfo = ref({ height: 0, heading: 0, pitch: 0 })
const selectedEntity = ref<any>(null)
const cesiumManager = ref<CesiumManager | null>(null)
const modelLoader = ref<ModelLoader | null>(null)
const currentModel = ref<any>(null)

// 预设位置
const locations = {
  beijing: { longitude: 116.397, latitude: 39.909, height: 10000 },
  shanghai: { longitude: 121.473, latitude: 31.230, height: 10000 },
  global: { longitude: 0, latitude: 0, height: 15000000 }
}

// 初始化应用
const initApp = async () => {
  try {
    loading.value = true
    loadingMessage.value = '正在初始化Cesium...'

    // 初始化Cesium场景
    cesiumManager.value = new CesiumManager('cesiumContainer')
    await cesiumManager.value.init()

    // 初始化模型加载器
    if (cesiumManager.value.viewer) {
      modelLoader.value = new ModelLoader(cesiumManager.value.viewer)
    }

    // 设置坐标更新回调
    cesiumManager.value.onCoordinatesUpdate = (lon: number, lat: number) => {
      coordinates.value = { longitude: lon, latitude: lat }
    }

    // 设置实体选择回调
    cesiumManager.value.onEntitySelected = (entity: any) => {
      selectedEntity.value = entity
      if (entity) {
        modelInfo.value = `已选中: ${entity.name || '未命名模型'}`
      } else {
        modelInfo.value = currentModel.value ? `当前模型: ${currentModel.value.name}` : '未加载模型'
      }
    }

    // 监听相机变化
    if (cesiumManager.value.viewer) {
      const camera = cesiumManager.value.viewer.camera
      camera.changed.addEventListener(() => {
        const position = camera.positionCartographic
        if (position) {
          cameraInfo.value = {
            height: Math.round(position.height),
            heading: Math.round(camera.heading * 180 / Math.PI),
            pitch: Math.round(camera.pitch * 180 / Math.PI)
          }
        }
      })
    }

    loading.value = false
    console.log('应用初始化完成')
  } catch (error) {
    console.error('应用初始化失败:', error)
    loadingMessage.value = '初始化失败: ' + (error as Error).message
  }
}

// 模型控制事件处理
const handleLoadModel = async (file: File, position: ModelPosition) => {
  try {
    loading.value = true
    loadingMessage.value = '正在加载模型...'

    if (currentModel.value && modelLoader.value) {
      modelLoader.value.removeModel(currentModel.value)
    }

    if (modelLoader.value) {
      currentModel.value = await modelLoader.value.loadFromFile(file, position)
      if (currentModel.value && cesiumManager.value) {
        cesiumManager.value.flyToEntity(currentModel.value)
        modelInfo.value = `已加载: ${file.name}`
      }
    }

    loading.value = false
  } catch (error) {
    console.error('模型加载失败:', error)
    loadingMessage.value = '模型加载失败: ' + (error as Error).message
    loading.value = false
  }
}

const handleLoadTestCube = async () => {
  try {
    loading.value = true
    loadingMessage.value = '正在加载测试立方体...'

    if (currentModel.value && modelLoader.value) {
      modelLoader.value.removeModel(currentModel.value)
    }

    if (modelLoader.value) {
      currentModel.value = modelLoader.value.createTestCube()
      if (currentModel.value && cesiumManager.value) {
        await cesiumManager.value.flyToEntity(currentModel.value)
        modelInfo.value = '已加载: 测试立方体 (10km×10km×100m)'
      }
    }

    loading.value = false
  } catch (error) {
    console.error('测试立方体加载失败:', error)
    loadingMessage.value = '测试立方体加载失败: ' + (error as Error).message
    loading.value = false
  }
}

const handleRemoveModel = () => {
  if (currentModel.value && modelLoader.value) {
    modelLoader.value.removeModel(currentModel.value)
    currentModel.value = null
    modelInfo.value = '未加载模型'
  }
}

const handleCenterOnModel = () => {
  if (currentModel.value && cesiumManager.value) {
    cesiumManager.value.flyToEntity(currentModel.value)
  }
}

const handleUpdatePosition = (position: ModelPosition) => {
  if (currentModel.value && modelLoader.value) {
    modelLoader.value.updatePosition(
      currentModel.value, 
      position.longitude, 
      position.latitude, 
      position.height
    )
  }
}

const handleUpdateOrientation = (orientation: ModelOrientation) => {
  if (currentModel.value && modelLoader.value) {
    modelLoader.value.updateOrientation(
      currentModel.value,
      orientation.heading,
      orientation.pitch,
      orientation.roll
    )
  }
}

const handleUpdateScale = (scale: number) => {
  if (currentModel.value && modelLoader.value) {
    modelLoader.value.updateScale(currentModel.value, scale)
  }
}

// 视图控制事件处理
const handleResetView = () => {
  cesiumManager.value?.resetView()
}

const handleFlyToLocation = (location: string) => {
  if (cesiumManager.value && locations[location as keyof typeof locations]) {
    const pos = locations[location as keyof typeof locations]
    cesiumManager.value.flyTo(pos.longitude, pos.latitude, pos.height)
  }
}

const handleChangeViewMode = (mode: string) => {
  if (!cesiumManager.value?.viewer) return
  
  const scene = cesiumManager.value.viewer.scene
  switch (mode) {
    case '3D':
      scene.morphTo3D(2.0)
      break
    case '2D':
      scene.morphTo2D(2.0)
      break
    case 'CV':
      scene.morphToColumbusView(2.0)
      break
  }
}

const handleChangeBasemap = (basemap: string) => {
  if (!cesiumManager.value?.viewer) return
  
  // 这里可以根据basemap参数切换不同的底图
  console.log('切换底图:', basemap)
}

const handleUpdateCameraHeight = (height: number) => {
  if (!cesiumManager.value?.viewer) return
  
  const camera = cesiumManager.value.viewer.camera
  const position = camera.positionCartographic
  if (position) {
    camera.setView({
      destination: Cesium.Cartesian3.fromRadians(
        position.longitude,
        position.latitude,
        height
      )
    })
  }
}

const handleToggleTerrain = (enabled: boolean) => {
  if (!cesiumManager.value?.viewer) return
  
  const scene = cesiumManager.value.viewer.scene
  scene.globe.depthTestAgainstTerrain = enabled
}

const handleToggleAtmosphere = (enabled: boolean) => {
  if (!cesiumManager.value?.viewer) return
  
  const scene = cesiumManager.value.viewer.scene
  if (scene.skyAtmosphere) {
    scene.skyAtmosphere.show = enabled
  }
}

const handleToggleLighting = (enabled: boolean) => {
  if (!cesiumManager.value?.viewer) return
  
  const scene = cesiumManager.value.viewer.scene
  scene.globe.enableLighting = enabled
}

const handleSaveView = () => {
  if (!cesiumManager.value?.viewer) return
  
  const camera = cesiumManager.value.viewer.camera
  const position = camera.positionCartographic
  if (position) {
    const viewData = {
      longitude: position.longitude * 180 / Math.PI,
      latitude: position.latitude * 180 / Math.PI,
      height: position.height,
      heading: camera.heading * 180 / Math.PI,
      pitch: camera.pitch * 180 / Math.PI,
      roll: camera.roll * 180 / Math.PI
    }
    console.log('保存视图:', viewData)
    // 这里可以保存到本地存储或发送到服务器
  }
}

// 界面控制
const toggleFullscreen = () => {
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen()
  } else {
    document.exitFullscreen()
  }
}

const toggleHelp = () => {
  alert('Cesium + Revit 三维模型展示系统\n\n操作说明:\n- 左侧面板: 模型文件加载和控制\n- 右侧面板: 视图控制和场景设置\n- 鼠标左键拖拽: 旋转视角\n- 鼠标右键拖拽: 平移视角\n- 鼠标滚轮: 缩放视角')
}

// 生命周期
onMounted(() => {
  initApp()
})

onUnmounted(() => {
  if (cesiumManager.value) {
    cesiumManager.value.destroy()
  }
})
</script>

<style scoped>
.app {
    width: 100%;
    height: 100%;
    position: relative;
    margin: 0;
    padding: 0;
    overflow: hidden;
}

#cesiumContainer {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    overflow: hidden;
    z-index: 1;
}
</style>